<template>
  <div>
    <el-tag
      v-for="(tag, index) in value_"
      :key="tag"
      class="mx-1"
      closable
      :disable-transitions="false"
      @close="handleClose(index)"
    >
      {{ tag }}
    </el-tag>
    <el-input
      v-if="inputVisible"
      ref="InputRef"
      v-model="inputValue"
      class="ml-1 w-20"
      size="small"
      @keyup.enter="handleInputConfirm"
      @blur="handleInputConfirm"
    />
    <el-button v-else class="button-new-tag ml-1" size="small" @click="showInput">
      <el-icon><i-ep-plus /></el-icon>
    </el-button>
  </div>
</template>

<script lang="ts" setup>
  import { computed, nextTick, ref } from 'vue';
  import { ElInput } from 'element-plus';
  import { Option } from '../form';

  const props = defineProps<{
    modelValue?: Array<Option>;
  }>();

  const emit = defineEmits(['update:modelValue']);

  const value_ = computed({
    get: () => props.modelValue || [],
    set: (v) => emit('update:modelValue', v)
  });

  const inputValue = ref('');
  const inputVisible = ref(false);
  const InputRef = ref<InstanceType<typeof ElInput>>();

  const handleClose = (index: number) => {
    value_.value.splice(index, 1);
  };

  const showInput = () => {
    inputVisible.value = true;
    nextTick(() => {
      InputRef.value?.input?.focus();
    });
  };

  const handleInputConfirm = () => {
    if (inputValue.value) {
      value_.value.push(inputValue.value);
    }
    inputVisible.value = false;
    inputValue.value = '';
  };
</script>

<style scoped></style>
